package com.xyyhome.config;

import com.xyyhome.common.YAjaxException;
import com.xyyhome.common.YConstant;
import com.xyyhome.common.YException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * 捕捉异常的AOP, 捕捉controller包下结尾为Controller的class的所有有RequestMapping注解的方法
 * + 日志
 * Created by ty850 on 2017/5/12.
 */
@Component
@Aspect
public class YControllerAOP {

    //@Pointcut("execution(* com.xyyhome.web..controller..*(..)) && @annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void around(){}

    //@Around("around()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        System.out.println(request.getRequestURL().toString());


        Object result;
        try {
            result = pjp.proceed();
        } catch (Exception e) {
            Method method = ((MethodSignature) pjp.getSignature()).getMethod();

            if (method.isAnnotationPresent(ResponseBody.class) || method.getDeclaringClass().isAnnotationPresent(RestController.class)) {
                // 如果有ResponseBody获取类上有RestController注解
                if (e instanceof YAjaxException)
                    throw e;
                else if (e instanceof YException)
                    throw new YAjaxException(e.getMessage());
                else
                    throw new YAjaxException(YConstant.UNKNOWN_EXCEPTION);
            } else {
                // 如果没有ResponseBody
                if (e instanceof YAjaxException)
                    throw new YException(e.getMessage());
                else if (e instanceof YException)
                    throw e;
                else
                    throw new YException(YConstant.UNKNOWN_EXCEPTION);
            }
        }

        return result;
    }
}
